#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#define PORT 8888
void sig_pip(int sign)
{
    printf("catch a sigpipe signal");
}
void sig_int(int sign)
{
    printf("catch a sigint signal");
    exit(0);
}
int main(void)
{
    signal(SIGPIPE, sig_pip);
    signal(SIGINT, sig_int);
    int clientfd;
    int err;
    clientfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    struct in_addr localIp;
    inet_aton("127.0.0.1", &localIp);
    server_addr.sin_addr.s_addr = localIp.s_addr;
    err = connect(clientfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (err == -1)
    {
        printf("connect failed\n");
        return -1;
    }
    else
    {
        printf("connect successed\n");
    }
    char buffer[1024] = "hello world!";
    write(clientfd, buffer, strlen(buffer) + 1);
    recv(clientfd, buffer, 1024, 0);
    printf("%s\n", buffer);
    while (1)
    {
        scanf("%s", buffer);
        write(clientfd, buffer, strlen(buffer) + 1);
        recv(clientfd, buffer, 1024, 0);
        printf("%s\n", buffer);
    }
    
    return 0;
}